/**
 * Created by Administrator on 18-6-10.
 */
ioclientMap = {}

var wstcp = (function () {
    function wstcp(name) {

        this.name = name;
    };
    wstcp.prototype.newConnect = function (url, connectCb, disconnectCb, dataCb) {

        //cc.log('callback in sio connect ',self.connectCallBack);
        var n = 0;
        for (var uuid in ioclientMap) {
            n++;
        }
        if (n >= 1) {
            //console.log('同时只能保持一个链接',url)
            //return;
        }
        console.log('new connect url ', url)
        if (!window.proto) {
            console.log('no protoc ', url)
            return;
        }
        var gameMsg = proto.lookup("pb.Msg");

        var sio = new WebSocket(url);
        sio.uuid = new Date().getTime();
        ioclientMap[sio.uuid] = sio;
        console.log("newConnect uuid ", sio.uuid);
        sio.gameMsg = gameMsg;
        sio.binaryType = "arraybuffer";

        sio.connectCb = connectCb;
        sio.disconnectCb = disconnectCb;
        sio.dataCb = dataCb;

        sio.onerror = function (evt) {
            console.log('connect_error ')
            setTimeout(function () {
                sio.connectIng = false;

                if (sio.disconnectCb) sio.disconnectCb(sio);
                //                if(callback)  callback(sio);
            }, 5000);
        }
        sio.onclose = function (evt) {
            delete ioclientMap[sio.uuid];
            sio.onDisconnect(sio);
        }
        sio.onopen = function (evt) {
            sio.onConnect(sio);
        }

        sio.onmessage = function (evt) {
            sio.tick = new Date().getTime();
            //console.log("recv msg ",typeof evt.data);
            if (typeof evt.data === String) {
                console.log("Received data string");
            }

            if (evt.data instanceof ArrayBuffer) {
                var buffer = evt.data;

                sio.sioConnected = true;
                var msg = sio.gameMsg.decode(new Uint8Array(buffer));
                if (msg && msg.event == EventKeepAlive) {
                    var ms = new Date().getTime() - sio.aliveTick;
                    sio.delayTime = ms;
                    if (sio.updateDelay) sio.updateDelay(ms);
                    return;
                }
                var len = buffer.byteLength;
                var n = 0;
                for (var k in msg) {
                    var v = msg[k]
                    if (v != null) {
                        if (msg.hasOwnProperty(k))
                            n++;
                    }
                }
                if (n > 0) {
                    // console.log("data len=" + len)
                    // console.log(JSON.stringify(msg)); // Correctly decoded
                }

                //cc.log('recv data ....');

                if (sio.dataCb) sio.dataCb(msg);

            }

        }




        //laya.eventMap['onConnect']=cb;

        //建立连接
        sio.onConnect = function () {
            console.log('onConnect wsio ++++++++++++++++++++++ ', sio.uuid);
            sio.connectIng = false;
            sio.sioConnected = true;
            var func = laya.eventMap['onConnect'];
            var self = this;

            this.tick = new Date().getTime();
            this.recvTick = new Date().getTime();
            sio.aliveTick = new Date().getTime();
            sio.timer = setInterval(function () {
                //return;
                var time = (new Date().getTime() - self.tick) / 1000;
                if (time > 3) {
                    console.log('socket timeout 10s ++++++++++++++++++++++++++++++++++++', sio.uuid);
                    sio.tick = new Date().getTime();
                    sio.sioConnected = false;
                    var callback = laya.eventMap['lostConnect'];
                    //if(callback)  callback(sio);
                    if (sio.disconnectCb) sio.disconnectCb(sio);
                    if (sio.close) sio.close();
                    clearInterval(sio.timer);
                    return;
                }
                var time1 = (new Date().getTime() - sio.aliveTick) / 1000;
                if (time1 >= 1) {
                    sio.aliveTick = new Date().getTime();
                    var keepAliveEvt = 28;
                    var m1 = gameMsg.create({
                        event: EventKeepAlive
                    });
                    var buf = gameMsg.encode(m1).finish();
                    if (sio.sioConnected)
                        sio.send(buf);
                }
            }, 500);
            //if(func) func();
            if (sio.connectCb) sio.connectCb(sio);
        }


        sio.onDisconnect = function () {
            console.log('sio.onDisconnect ++++++++++++++++++++++++++++', sio.uuid);
            var callback = laya.eventMap['lostConnect'];
            sio.sioConnected = false;
            setTimeout(function () {
                // if(callback)  callback();
                //if(sio.disconnectCb)  sio.disconnectCb(sio);
                sio.sioConnected = false;
            }, 1000);

        }

        return sio;
    }

    return wstcp;
}());